package com.lafeier.beefirm;

import com.lafeier.beefirm.antlr4.BeefirmLexer;
import com.lafeier.beefirm.antlr4.BeefirmParser;
import com.lafeier.beefirm.parser.BeefirmAstBuilder;
import com.lafeier.beefirm.parser.BeefirmDraw;
import com.lafeier.beefirm.tree.JavaCode;
import lombok.SneakyThrows;
import net.sourceforge.plantuml.code.Transcoder;
import net.sourceforge.plantuml.code.TranscoderUtil;
import org.antlr.v4.runtime.*;

import java.io.IOException;

public class Beefirm {
    public static void main(String[] args) throws IOException {
        if (args.length < 1) {
            System.err.println("必须提供beefirm定义文件!");
            System.exit(-1);
        }
        boolean onlyUrl = false;
        for (int i = 0; i < args.length; i++) {
            if (args[i].contains("-url")) {
                onlyUrl = true;
            }
        }
        BeefirmLexer beefirmLexer = new BeefirmLexer(CharStreams.fromFileName(args[0]));
        BeefirmParser beefirmParser = new BeefirmParser(new CommonTokenStream(beefirmLexer));
        beefirmParser.addErrorListener(new BaseErrorListener(){
            @SneakyThrows
            @Override
            public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
                throw new Exception("line " + line + ":" + charPositionInLine + " " + msg);
            }
        });
        BeefirmParser.JavaCodeContext javaCodeContext = beefirmParser.javaCode();
        JavaCode javaCode = (JavaCode) javaCodeContext.accept(new BeefirmAstBuilder());
        BeefirmDraw beefirmDraw = new BeefirmDraw(javaCode);
        String content = beefirmDraw.getContent();
        if (onlyUrl) {
            Transcoder transcoder = TranscoderUtil.getDefaultTranscoder();
            String prefix = "http://www.plantuml.com/plantuml/png/";
            System.out.println(prefix + transcoder.encode(content));
        } else {
            System.out.println(content);
        }


    }


}
